package service.impl;


import dao.HouseholdDao;
import dao.impl.HouseholdDaoImpl;
import entity.Household;
import service.HouseholdrService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pengrui
 * @version 1.0
 * @date 2021/9/8 18:27
 * @Description 住户管理Service实现类
 */
public class HouseholdServiceImpl implements HouseholdrService {

    HouseholdDao householdDao =  new HouseholdDaoImpl();
    //查找表中的所有数据
    public Map<String,Object> searchAll(int page, int limit){

        Map<String,Object> result = new HashMap<>();

        List<Household> list = householdDao.getAllHousehold(page,limit);
        int count = householdDao.getCountByHousehold();
        System.out.println(count);
        result.put("data",list);
        result.put("count",count);
        result.put("code",0);
        return result;
    }
    //向表中存储数据（插入和更新）
    public Map<String,Object> saveHousehold(Household household) {
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            if(!householdDao.select(household)){
                map.put("success",householdDao.insert(household));
                map.put("msg", "插入成功");
            }else {
                map.put("success", householdDao.update(household));
                map.put("msg", "修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "操作失败!");
        }
        return map;
    }
    //删除操作
    public Map<String,Object> deleteHousehold(String id){

        Map<String,Object> map=new HashMap();
        String[] strs = id.split(",");

        List<Integer> list = new ArrayList<>();

        for(int i = 0;i < strs.length;i ++){
            list.add(Integer.parseInt(strs[i]));
        }
        if(list.size() > 1 ){
            if (householdDao.deleteByIds(list)){
                map.put("success",true);
                map.put("msg", "批量删除成功");
            }
            else {
                map.put("success",false);
                map.put("msg", "批量删除失败");
            }
        }else if(list.size() == 1 ){
            if (householdDao.deleteById(list)){
                map.put("success",true);
                map.put("msg", "删除成功");
            }
            else{
                map.put("success",false);
                map.put("msg", "删除失败");
            }
        }

        return map;
    }

}
